package com.luhuihahaha.jsoupdemo.util;

import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Component
public class HttpUtils {

    static List<String> USER_AGENT = new ArrayList<String>(10) {
        {
            add("Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19");
            add("Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
            add("Mozilla/5.0 (Linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
            add("Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
            add("Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0");
            add("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36");
            add("Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19");
            add("Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
            add("Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3");
        }
    };

    private PoolingHttpClientConnectionManager cm;


    //初始化连接池
    public HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();


        //设置最大连接数
        this.cm.setMaxTotal(100);


        //设置最大主机连接数
        this.cm.setDefaultMaxPerRoute(10);

    }

    /***
     * 根据请求地址下载页面数据
     * @param url
     * @return 页面数据
     */
    public String doGetHtml(String url){
        //获取httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();

        //设置httpget请求对象，设置url
        HttpGet httpGet = new HttpGet(url);

        //设置请求信息
        httpGet.setConfig(this.getconfig());

        CloseableHttpResponse response = null;

        //使用httpclient发起请求，
        try {
             response = httpClient.execute(httpGet);


             if (response.getStatusLine().getStatusCode()==200){
                 //判断entity是否为空，不为空则能使用
                 if(response.getEntity()!=null){
                     String content = EntityUtils.toString(response.getEntity(), "utf-8");
                     System.out.println("我执行了");
                     return content;
                 }
             }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        //有问题则返回空串
        return "";
    }

    /***
     * 根据请求地址下载图片
     * @param url
     * @return 图片名称
     */
    public String doGetImage(String url){
        //获取httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();

        //设置httpget请求对象，设置url
        HttpGet httpGet = new HttpGet(url);
        Header header = new BasicHeader("User-Agent",randomUserAgent());
        httpGet.setHeader(header);

        //设置请求信息
        httpGet.setConfig(this.getconfig());

        CloseableHttpResponse response = null;

        //使用httpclient发起请求，
        try {
            response = httpClient.execute(httpGet);


            if (response.getStatusLine().getStatusCode()==200){
                //判断entity是否为空，不为空则能使用
                if(response.getEntity()!=null){
                    //下载图片
                    //获取图片后缀
                    String extName = url.substring(url.lastIndexOf("."));

                    //创建图片名，重命名图片
                    String pickName = UUID.randomUUID().toString()+extName;

                    //下载图片

                    //声明outputStream
                    OutputStream outputStream = new FileOutputStream(new File("C:\\Users\\tyliones\\Desktop\\images\\"+pickName));

                    response.getEntity().writeTo(outputStream);


                    //返回图片名称
                    return pickName;

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        //有问题则返回空串
        return "";
    }


    public RequestConfig getconfig() {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(10000)
                                                 .setSocketTimeout(5000)
                                                 .setConnectionRequestTimeout(100000).build();
    return config;
    }

    public String randomUserAgent() {
        Random random = new Random();
        int num = random.nextInt(USER_AGENT.size());
        return USER_AGENT.get(num);
    }


}
